/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.framework.base.dao;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ImplicitBasicColumnNameSource;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;

/**
 * The Class HibernateImplicitNamingStrategy.
 *
 * @author Xi Wei
 */
public class HibernateImplicitNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl {

	/* (non-Javadoc)
	 * @see org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl#determineBasicColumnName(org.hibernate.boot.model.naming.ImplicitBasicColumnNameSource)
	 */
	@Override
    public Identifier determineBasicColumnName(ImplicitBasicColumnNameSource source) {
        return convert(source);
    }

    private Identifier convert(ImplicitBasicColumnNameSource source) {
        if (StringUtils.isBlank(transformAttributePath(source.getAttributePath()))) {
            return toIdentifier(transformAttributePath(source.getAttributePath()), 
                                source.getBuildingContext());
        }

        String regex = "([a-z])([A-Z])";
        String replacement = "$1_$2";
        String newName = transformAttributePath(source.getAttributePath())
                .replaceAll(regex, replacement).toLowerCase();
        return toIdentifier(newName, source.getBuildingContext());
    }
}
